package com.imooc.miaosha.exception;

import com.imooc.miaosha.result.CodeMsg;
import com.imooc.miaosha.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author simple
 * @version 1.0
 * @date 2018/6/16 22:15
 */
@Slf4j
@ControllerAdvice
@ResponseBody
public class GlobeExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result handler(HttpServletRequest request, Exception e) {
        if (e instanceof BindException) {
            log.error("have exception", e);
            List<ObjectError> allErrors = ((BindException) e).getAllErrors();
            ObjectError objectError = allErrors.get(0);
            String message = objectError.getDefaultMessage();
            return Result.error(CodeMsg.BIND_ERROR.fillArgs(message));
        }
        return Result.error(CodeMsg.SERVER_ERROR);
    }

    @ExceptionHandler(MiaoShaException.class)
    public String miaoShaExceptionHandler(MiaoShaException e) {
        return e.getMessage();
    }
}
